package com.hhhn.wk.main.tab4.allorder.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.main.tab4.allorder.activity.starsendgoos.ApplyActivity;
import com.hhhn.wk.main.tab4.allorder.entity.ItemGoodsBean;
import com.hhhn.wk.main.tab4.allorder.entity.MyOrder;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.wkpulltorefreshlayout.ViewStatus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/16 0016    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 待发货详情  03
 * * * * * * * * * * * */
public class StarSendGoosActivity extends BaseActivity {
    private TextView tv_goRefund;//批量退款
    public static ArrayList<MyOrder> mArrayList = new ArrayList<MyOrder>();
    //listview
    private ListView mLoadListView;
    List<ItemGoodsBean> orderDetailVoList;//商品数组
    private static MyAdaper<ItemGoodsBean> mAdapter;
    private BaseActivity activity;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setData0();
                    setData();
                    break;
            }
        }
    };
    private TextView tv_orderNumber;//订单编号
    private TextView tv_creationTime;//下单时间
    private TextView tv_sendType;//配送方式
    private TextView tv_takeGoodsUserName;//收货-姓名
    private TextView tv_takeGoodsUserPhone;//收货-手机号
    private TextView tv_takeGoodsUserAddress;//收货-地址

    private TextView tv_goodsMoney;//商品总额
    private TextView tv_goodsfreight;//运费
    private TextView tv_totalPrice;//需付款
    private TextView tv_deductible_amount;//抵扣金额
    private TextView tv_actualPayment;//实付款

    private LinearLayout ll_refund_money;//已成功退款显示出此空间
    private TextView tv_refundMoney;//已成功退款显示出此空间
    private void setData0() {
        tv_orderNumber.setText(mArrayList.get(0).getOrder_codeId());
        tv_creationTime.setText(mArrayList.get(0).getOrder_time());
        tv_sendType.setText(mArrayList.get(0).getReceivingWay());
        tv_takeGoodsUserName.setText(mArrayList.get(0).getAddr_name());
        tv_takeGoodsUserPhone.setText(mArrayList.get(0).getAddr_tel());
        tv_takeGoodsUserAddress.setText(mArrayList.get(0).getAddr_txt());
        tv_goodsMoney.setText("￥"+AllPublic.priceGSH(mArrayList.get(0).getOrder_money()));
        tv_goodsfreight.setText("￥"+AllPublic.priceGSH(mArrayList.get(0).getFreight()));
        tv_totalPrice.setText("￥"+AllPublic.priceGSH(mArrayList.get(0).getTotalPrice()));
        tv_deductible_amount.setText("￥"+AllPublic.priceGSH(mArrayList.get(0).getDeductibleAmount()));
        tv_actualPayment.setText("实际付款：￥"+AllPublic.priceGSH(mArrayList.get(0).getActualPayment()));
        dismissLoad();
    }
    private String id="";
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_star_send_goos);
        Intent intent=getIntent();
        activity=this;
        id=  intent.getStringExtra("id");
    }
    @Override
    protected void initView() {
        tv_goRefund=findViewById(R.id.tv_goRefund);
        mLoadListView = findViewById(R.id.mLoadListView);
        tv_orderNumber = findViewById(R.id.tv_orderNumber);
        tv_creationTime = findViewById(R.id.tv_creationTime);
        tv_sendType = findViewById(R.id.tv_sendType);
        tv_takeGoodsUserName = findViewById(R.id.tv_takeGoodsUserName);
        tv_takeGoodsUserPhone = findViewById(R.id.tv_takeGoodsUserPhone);
        tv_takeGoodsUserAddress = findViewById(R.id.tv_takeGoodsUserAddress);
        tv_goodsMoney = findViewById(R.id.tv_goodsMoney);
        tv_goodsfreight = findViewById(R.id.tv_goodsfreight);
        tv_actualPayment = findViewById(R.id.tv_actualPayment);
        tv_totalPrice = findViewById(R.id.tv_totalPrice);
        tv_deductible_amount = findViewById(R.id.tv_deductible_amount);
        ll_refund_money = findViewById(R.id.ll_refund_money);
        tv_refundMoney = findViewById(R.id.tv_refundMoney);

    }
    @Override
    protected void initData() {
        getJSON();
    }
    @Override
    protected void initClick() {
        tv_goRefund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toastWk("批量退款");
            }
        });
    }
    private void setData() {
        if (mAdapter == null) {
            mAdapter = new MyAdaper<ItemGoodsBean>(orderDetailVoList, R.layout.item_order_within) {
                @Override
                public void bindView(ViewHolder holder,final  ItemGoodsBean obj,final int position) {
                    holder.setImageyuan(R.id.tv_goodsImg,obj.getGoodsImg());
                    holder.setText(R.id.tv_goodsName, obj.getGoodsName());
                    holder.setText(R.id.tv_goodsMoney, "￥" + obj.getGoodsMoney());
                    holder.setText(R.id.tv_goodsNumber, "X" + obj.getGoodsNumber());
                    holder.setVisibility(R.id.ll_btn_xq,VISIBLE);
                    // 0 申请退款， 103401 买家申请退款（申请中），103402 卖家同意退款(退款成功) , 103403 卖家拒绝退款 ,
                    switch (obj.getRefund_status()){
                        case 0:
                            holder.setText(R.id.tv_btn, "申请退款");//申请退款--申请中--退款成功
                            break;
                        case 103401:
                            holder.setText(R.id.tv_btn, "申请中...");//申请退款--申请中--退款成功
                            break;
                        case 103402:
                            holder.setText(R.id.tv_btn, "退款成功");//申请退款--申请中--退款成功
                            ll_refund_money.setVisibility(VISIBLE);
                            tv_refundMoney.setText("￥" +mArrayList.get(0).getRefund_fee());
                            break;
                        case 103403:
                            holder.setText(R.id.tv_btn, "拒绝退款");//申请退款--申请中--退款成功--拒绝退款
                            break;
                    }

                    holder.setOnClickListener(R.id.tv_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // 0 申请退款， 103401 买家申请退款（申请中），103402 卖家同意退款(退款成功) , 103403 卖家拒绝退款 ,
                            switch (obj.getRefund_status()){
                                case 0:
//                                    holder.setText(R.id.tv_btn, "申请退款");//申请退款--申请中--退款成功
                                    Intent intent=new Intent(activity, ApplyActivity.class);
                                    List<ItemGoodsBean>  lstBean=new ArrayList<ItemGoodsBean>();
                                    ItemGoodsBean goodsBean=new ItemGoodsBean();
                                    goodsBean.setGoodsID(obj.getGoodsID());
                                    goodsBean.setGoodsImg(obj.getGoodsImg());
                                    goodsBean.setGoodsMoney(obj.getGoodsMoney());
                                    goodsBean.setGoodsName(obj.getGoodsName());
                                    goodsBean.setGoodsNumber(obj.getGoodsNumber());
                                    goodsBean.setOrder_pro_id(obj.getOrder_pro_id());
                                    lstBean.add(goodsBean);
                                    intent.putExtra("lstBean", (Serializable) lstBean);
                                    intent.putExtra("position",position);
                                    startActivityForResult(intent,1);
                                    break;
                                case 103401:
                                    toastWk("申请中，请耐心等待！");
                                    break;
                                case 103402:
                                    ll_refund_money.setVisibility(VISIBLE);
                                    tv_refundMoney.setText( "￥" +mArrayList.get(0).getRefund_fee());
                                    break;
                                case 103403:
                                    break;
                            }
                        }
                    });
                }
            };
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mLoadListView.setAdapter(mAdapter);
        dismissLoad();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mArrayList!=null){
            mArrayList.clear();
        }
        if (orderDetailVoList!=null){
            orderDetailVoList.clear();
        }
        if (mAdapter!=null){
            mAdapter=null;
        }
    }

    private void getJSON() {
        showLoad();
        RequestParams params = AllPublic.getParamsProductOrder(activity, "/orderStatusInfo", false);
        params.addParameter("orderId",id);

        Log.d("@@", "params: " + params);
        //请求
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("待发货详情", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {//成功
                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONObject orderInfo = data.getJSONObject("orderInfo");

//                        if (records.length() < Config.ROWS) {
//                            isWU = true;
//                        }
                        MyOrder myOrder = null;
                        ItemGoodsBean mItemGoodsBean;

                            int channel = orderInfo.has("channel") ? orderInfo.getInt("channel") : 0;//id
                            String orderid = orderInfo.has("orderCode") ? orderInfo.getString("orderCode") : "";//订单编号id
                            String cmIndate = orderInfo.has("cmIndate") ? orderInfo.getString("cmIndate") : "";//创建时间


                            String addr_name = orderInfo.has("addrName") ? orderInfo.getString("addrName") : "";//收货人姓名
                            String addr_tel = orderInfo.has("addrTel") ? orderInfo.getString("addrTel") : "";//收货人电话
                            String addr_txt = orderInfo.has("addrTxt") ? orderInfo.getString("addrTxt") : "";//收货人地址
                            String receivingWay = orderInfo.has("receivingWay") ? orderInfo.getString("receivingWay") : "";//配送方式
                            String refund_fee = orderInfo.has("refundMoney") ? orderInfo.getString("refundMoney") : "";//退款金额





                        String total_product = orderInfo.has("totalProduct") ? orderInfo.getString("totalProduct") : "";//商品价格
                        String freight = orderInfo.has("freight") ? orderInfo.getString("freight") : "";//运费
                        String totalPrice = orderInfo.has("money") ? orderInfo.getString("money") : "";//结算价格（	需要支付金额）
                        String deductibleAmount = orderInfo.has("deductibleAmount") ? orderInfo.getString("deductibleAmount") : "";//抵扣金额
                        String actualPayment = orderInfo.has("orderJs") ? orderInfo.getString("orderJs") : "";//实际.

                            myOrder = new MyOrder();


                            myOrder.setRefund_fee(refund_fee);
                            myOrder.setTotalPrice(totalPrice);
                            myOrder.setOrder_codeId(orderid);
                            myOrder.setOrder_time(cmIndate);
                            myOrder.setOrder_money(total_product);
                            myOrder.setFreight(freight);


                            myOrder.setAddr_name(addr_name);
                            myOrder.setAddr_tel(addr_tel);
                            myOrder.setAddr_txt(addr_txt);
                            myOrder.setReceivingWay(receivingWay);
                            myOrder.setActualPayment(actualPayment);
                            myOrder.setDeductibleAmount(deductibleAmount);


                            JSONArray productInfo = data.getJSONArray("productInfo");
                            orderDetailVoList = new ArrayList<ItemGoodsBean>();//商品数组
                            for (int j = 0; j < productInfo.length(); j++) {
                                mItemGoodsBean = new ItemGoodsBean();
                                JSONObject sBean = productInfo.getJSONObject(j);
                                String product_name = sBean.has("productName") ? sBean.getString("productName") : "";//商品名称
                                int product_nums = sBean.has("productNums") ? sBean.getInt("productNums") : 0;//商品数量
                                String product_logo = sBean.has("productLogo") ? sBean.getString("productLogo") : "";//商品图片
                                String price_pf = sBean.has("priceJs") ? sBean.getString("priceJs") : "";//商品批发价

                                String order_pro_id = sBean.has("orderProId") ? sBean.getString("orderProId") : "";//商品退款订单
                                int refund_status = sBean.has("refundStatus") ? sBean.getInt("refundStatus") : 0;//商品退款状态

                                mItemGoodsBean.setOrder_pro_id(order_pro_id);
                                mItemGoodsBean.setRefund_status(refund_status);
                                mItemGoodsBean.setGoodsMoney(price_pf);
                                mItemGoodsBean.setGoodsName(product_name);
                                mItemGoodsBean.setGoodsNumber(product_nums);
                                mItemGoodsBean.setGoodsImg(product_logo);
                                orderDetailVoList.add(mItemGoodsBean);
                            }

                            myOrder.setBeanGoodsList(orderDetailVoList);
                            mArrayList.add(myOrder);

                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("待发货详情-第二个", ex + "");
                ex.printStackTrace();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("待发货详情-第三个", cex + "");
            }

            @Override
            public void onFinished() {
                Log.d("待发货详情-第四个", "onFinished");
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            if (mArrayList!=null){
                mArrayList.clear();
            }
            if (orderDetailVoList!=null){
                orderDetailVoList.clear();
            }
            if (mAdapter!=null){
                mAdapter=null;
            }
            getJSON();
        }

    }
}
